package org.example.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.ReferenceCountUtil;
import org.example.netty.handler.MsgStringHandler;
import org.example.utils.LogUtils;

import java.util.List;

public class NettyCustomServer {
    public static void main(String[] args) throws Exception {
        // 引导类，组装和集成器，负责将不同的netty组件组装在一起
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 定义boss事件轮询组，1表示内部有一个线程
        // 每个线程内部，一个反应器在轮询
        // 一个反应器对应一个Selector
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);

        // 定义worker事件轮询组
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        serverBootstrap.group(bossGroup, workerGroup);

        // 设置NIO
        serverBootstrap.channel(NioServerSocketChannel.class);

        // 绑定端口
        serverBootstrap.localAddress(8081);

        serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        // 5 装配子通道的流水线
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            /**
             * 有连接到达时会触发此方法
             * @param ch
             * @throws Exception
             */
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 自定义的一个处理器
                ch.pipeline().addLast(new CustomStringDecoder());
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new MsgStringHandler());
            }
        });

        try {
            // 开始绑定服务器，通过调用sync()同步阻塞直到绑定成功
            ChannelFuture future = serverBootstrap.bind().sync();
            LogUtils.info("服务器启动成功，监听端口：" + future.channel().localAddress());

            //
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 优雅关闭
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    /**
     * 字节转对象
     * TCP流可以视作一个无界流
     */
    static class CustomStringDecoder extends ByteToMessageDecoder {
        /**
         * 按照一定规则，一段一段解析流
         * @param ctx
         * @param in
         * @param out
         * @throws Exception
         */
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            // 首先读取长度字节，如果小于4，继续等
            if (in.readableBytes() < 4) {
                return;
            }

            in.markReaderIndex();
            int contentLength = in.readInt();
            if (in.readableBytes() < contentLength) {
                // readerIndex要重置到整数之前
                in.resetReaderIndex();
                return;
            }
            byte[] contents = new byte[contentLength];
            in.readBytes(contents);
            // 发往下一个地方
            out.add(new String(contents));
        }
    }

}
